import { ref } from 'vue';
import { Modal } from '@jecloud/ui';
import AddChild from './add-child.vue';
import { ChildFuncCustomizeSave } from '@/api/index';

/**
 *
 * @param {Object} options
 * @param {String} title 标题
 * @param {Function} callback 回调函数
 *
 */

export function AddChildModal(options) {
  const { title, callback, recordData } = options;
  const recordpropData = {
    title: title ? title : '添加子功能',
    ...recordData,
  };
  const dataRef = ref(recordpropData);
  const AddChildRef = ref();
  let modal = null; // 窗口对象
  const handleSave = function (btn, formState) {
    btn.loading = true;
    ChildFuncCustomizeSave({
      tableCode: 'JE_CORE_FUNCRELATION',
      FUNCRELATION_CODE: formState.FUNCRELATION_CODE,
      FUNCRELATION_FUNCINFO_ID: recordData.JE_CORE_FUNCINFO_ID,
      FUNCRELATION_NAME: formState.FUNCRELATION_NAME,
      FUNCRELATION_RELYONTYPE: formState.FUNCRELATION_RELYONTYPE,
    })
      .then((res) => {
        callback?.({ isRefresh: true });
        modal.close();
        Modal.message(res.message, 'success');
        btn.loading = false;
      })
      .catch((error) => {
        Modal.alert(error.message, 'error');
        btn.loading = false;
      });
  };
  // 确认操作
  const okButton = function ({ button }) {
    const { formState, formRef } = AddChildRef.value;
    formRef
      .validate()
      .then(() => {
        handleSave(button, formState);
      })
      .catch((error) => {
        console.error(error);
      });

    return false;
  };
  // 初始选中值
  const onShow = function ({ $modal }) {
    modal = $modal;
  };
  const AddChildSolt = () => {
    return (
      <AddChild
        ref={AddChildRef}
        recordData={dataRef.value}
        bodyBorder
        allowDeselect={false}
        onCellDblclick={okButton}
      />
    );
  };

  return Modal.window({
    title: dataRef.value.title,
    maximizable: false,
    width: '600px',
    height: 'auto',
    bodyStyle: { padding: '0 20px' },
    headerStyle: { height: '60px' },
    okButton: {
      closable: false,
      handler: okButton,
    },
    onShow,
    cancelButton: true,
    slots: {
      default: AddChildSolt,
    },
  });
}
